
// #ifdef APP-PLUS
// 默认权限列表集合
import { Authority_list as list } from './pulice.js'
import { Modal, Toast } from './uni_api'

/**
 * @查看用户是否开启某些必要权限
 * @Query_authority  查询权限
 * @Open_authority   开启权限
 * @screening        权限数据分解重组
 * @whether          查询哪些是权限否未开启
 * @ModTip           权限开通提示
 * @android          安卓系统权限
 * @ios              苹果系统权限
 * 
 */

class system_Authority {
    /**
     * @param { Array<object> | object } Authority 权限数组
     * @param { String } type 全部(all)|单独(任意) android上他会查询所有得 ios不支持查所有 所以默认第一个
     */
    constructor(Authority = list, type = 'all') {
        this.system = uni.getSystemInfoSync()
        this.Authority = Authority
        this.type = type
    }
    /**
     * @权限查询
     */
    Query_authority() {
        if (this.system.osName == 'ios') {
            if (this.type == 'all') {
                return this.ios(this.Authority[0].type)
            } else {
                return this.ios(this.Authority.type)
            }
        }
        if (this.system.osName == 'android') {
            if (this.type == 'all') {
                return this.android(this.Authority)
            } else {
                return this.android([this.Authority])
            }
        }
    }
    /**
     * @android系统  支持多个检测
     * @param { Array<Object> } Authority 权限数据
     */
    android(Authority) {
        return new android_Authority(this.screening(Authority), Authority, 'Authority').whether()
    }
    /**
     * @ios系统  只能单一检测
     * @param { Array<Object> } Authority 权限数据
     */
    ios(Authority) {
        return new ios_Authority(Authority).detection()
    }
    /**
     * @权限数据分解重组 
     * @param {  Array<object> } list 权限数组
     * @param { String } Authority_Str 未开启权限得字符
     * @param { Array<string> | String } type 返回值类型
     * @returns 
     */
    screening(list, Authority_Str = '', type = 'Authority') {
        // 返回权限
        if (type == 'Authority') {
            const Authority_list = list.reduce((pur, cur) => {
                pur.push(cur.Authority)
                return pur
            }, [])
            return Authority_list
        }
        // 返回权限提示
        if (type == 'text') {
            const Authority_text = list.reduce((pur, cur) => {
                Authority_Str.indexOf(cur.Authority) !== -1 && pur.push(cur.text)
                return pur
            }, [])
            return Array.from(new Set(Authority_text)).join()
        }
    }
    /**
     * @权限开通提示
     * @param { Array<Object> } Authority_list  权限数组
     * @param { String } strlist ios:提示信息  android: 权限字符串
     * @param { String } osName 系统
     */
    ModTip(Authority_list, strlist) {
        let tip = ''
        if (this.system.osName == 'android') {
            tip = this.screening(Authority_list, strlist, 'text')
        }
        if (this.system.osName == 'ios') {
            tip = strlist
        }
        const content = `您还没有开启${tip}等权限，将无法体验相关权限的功能，是否前往设置？`
        Modal('权限设置', content, '去设置').then(res => {
            this.Open_authority()
        }).catch(err => {
            Toast(`您还没有开启${tip}等权限，将无法体验相关权限的功能`)
            return Promise.reject()
        })

    }
    /**
     * @开启应用设置
     */
    Open_authority() {
        try {
            if (this.system.osName == 'android') {
                //获取宿主上下文
                let main = plus.android.runtimeMainActivity();
                // Intent机制来协助应用间的交互与通讯
                let Intent = plus.android.importClass("android.content.Intent");
                // 链接设置页面
                let PackageName = '应用包名'
                let mIntent = new Intent('android.settings.SOUND_SETTINGS', 'package:' + PackageName);
                // 开启新的页面(设置)
                main.startActivity(mIntent);
            }
            if (this.system.osName == 'ios') {
                // 引入页面应用程序链接实例
                let UIApplication = plus.ios.import("UIApplication")
                // 链接地址实例
                let NSURL = plus.ios.import("NSURL");
                // 返回设置页面url地址
                let setting = NSURL.URLWithString("app-settings:");
                // 打开应用页面的实例对象
                let application = UIApplication.sharedApplication();
                // 打开设置
                application.openURL(setting);
                // 清除实例对象
                plus.ios.deleteObject(setting);
                plus.ios.deleteObject(application);
            }
        } catch (err) {
            console.log(err)
        }
    }
}

/**
 * @安卓权限
 * @param { [String] } Authority 权限数组
 * @param { [Object] } Authority_list 权限数据完整数组
 */
class android_Authority {
    constructor(Authority, Authority_list) {
        this.Authority = Authority
        this.Authority_list = Authority_list
    }
    /**
      * @查询哪些是权限否未开启
      * @param { Array<string>} Authority 权限数组
      * @param { Array<object> } Authority_list 权限数组
     */
    whether() {
        plus.android.requestPermissions(this.Authority, function (e) {
            //权限被永久拒绝
            if (e.deniedAlways.length > 0) {
                // 弹出提示框解释为何需要定位权限，引导用户打开设置页面开启
                console.log('Always Denied!!! ' + e.deniedAlways.toString());
                return new system_Authority().ModTip(this.Authority_list, e.deniedAlways.toString())
            }
            //权限被临时拒绝
            if (e.deniedPresent.length > 0) {
                // 弹出提示框解释为何需要定位权限，可再次调用plus.android.requestPermissions申请权限
                console.log('Always Denied!!! ' + e.deniedAlways.toString());
                return new system_Authority().ModTip(this.Authority_list, e.deniedAlways.toString())
            }
            //权限被允许
            if (e.granted.length > 0) {
                //调用依赖获取定位权限的代码
                console.log('Granted!!! ' + e.granted.toString());
                return Promise.resolve()

            }
        }, function (e) {
            console.log('Request Permissions error:' + JSON.stringify(e));
            Toast(`设置失败,重新启动或者安装应用`)

        });
    }
}

/**
 * @ios单独检测权限
 * @param { string } this.type 权限类型
 * @detection 检测对应权限方法 执行对应权限函数
 */
class ios_Authority {
    constructor(type) {
        this.type = type
        this.item = ''
    }
    detection() {
        const system = system.osName
        list.forEach(cur => {
            if (cur.type == this.type) this.item = cur
        })
        let text = this.item.text
        switch (this.type) {
            case 'camera':
                return this.ios_camera(text)
            case 'location':
                return this.ios_location(text)
            case 'blue':
                return this.ios_bluetooth(text)
            case 'Photo':
                return this.ios_PhotoAlbum(text)
        }

    }
    // 位置权限
    ios_location() {
        return new Promise((resolve, reject) => {
            let cllocationManger = plus.ios.import("CLLocationManager");
            let status = cllocationManger.authorizationStatus();
            //2错误  !2成功    
            if (status == 2) {
                gotoAppPermissionSetting()
                reject(new system_Authority().ModTip('', text))

            } else {
                resolve(true)
            }
            plus.ios.deleteObject(cllocationManger);
        })

    }
    // 蓝牙权限
    ios_bluetooth(text) {
        const openblue = () => {
            uni.openBluetoothAdapter({
                success(res) {
                    return Promise.resolve(res)
                }
            })
        }
        return new Promise((resolve, reject) => {
            openblue().then(res => {
                /* 判断是否打开蓝牙 */
                uni.getBluetoothAdapterState({
                    success(res) {
                        //如果res.avaliable==false 说明没打开蓝牙 反之则打开
                        if (res.available == false) {
                            reject(new system_Authority().ModTip('', text))
                        } else {
                            //这里是我的业务
                            resolve(true)
                        }
                    }
                })
            })
        })

    }
    // 相机权限
    ios_camera(text) {
        return new Promise((resolve, reject) => {
            let AVCaptureDevice = plus.ios.import("AVCaptureDevice");
            let authStatus = AVCaptureDevice.authorizationStatusForMediaType('vide');
            // 开启3 !3未开启
            if (authStatus == 3) {
                resolve(true)
            } else {
                reject(new system_Authority().ModTip('', text))
            }
            plus.ios.deleteObject(AVCaptureDevice);
        })
    }
    // 相册权限
    ios_PhotoAlbum() {
        return new Promise((resolve, reject) => {
            let PHPhotoLibrary = plus.ios.import("PHPhotoLibrary");
            let authStatus = PHPhotoLibrary.authorizationStatus();
            if (authStatus == 3) {
                resolve(true)
            } else {
                reject(new system_Authority().ModTip('', text))
            }
            plus.ios.deleteObject(PHPhotoLibrary);
        })

    }
}
export default {
    system_Authority, android_Authority, ios_Authority
}
// #endif


